package com.zc.blog.util;

public class PageUtil {
    // 页面地址 // 总记录数 // 当前页 // 每页数量 // 查询参数
    public static String genPagation(String targetUrl, int totalNum, int currentPage, int pageSize, String query) {
        int totalPage = (totalNum % pageSize == 0) ? totalNum / pageSize : totalNum / pageSize + 1;
        StringBuilder pageCode = new StringBuilder();

        // 添加搜索条件参数
        String queryParams = "";
        if (query != null && !query.isEmpty()) {
            queryParams = "&query=" + query;
        }

        // 分页外框
        pageCode.append("<ul class='pagination'>");

        // 上一页
        if (currentPage == 1) {
            pageCode.append("<li class='disabled'><a href='#'><i class='fa fa-angle-left'></i></a></li>");
        } else {
            pageCode.append("<li><a href='#' onclick='return keepScrollPos(\"" + targetUrl + "?page=" + (currentPage - 1) + queryParams + "\");'><i class='fa fa-angle-left'></i></a></li>");
        }

        // 页码
        if (currentPage <= 2) { // 如果是前两页
            for (int i = 1; i <= 5 && i <= totalPage; i++) {
                if (i == currentPage) {
                    pageCode.append("<li class='active'><a href='#'>" + i + "</a></li>");
                } else {
                    pageCode.append("<li><a href='#' onclick='return keepScrollPos(\"" + targetUrl + "?page=" + i + queryParams + "\");'>" + i + "</a></li>");
                }
            }
        } else if (currentPage >= totalPage - 1) { // 如果是后两页
            for (int i = totalPage - 4; i <= totalPage; i++) {
                if (i > 0) {
                    if (i == currentPage) {
                        pageCode.append("<li class='active'><a href='#'>" + i + "</a></li>");
                    } else {
                        pageCode.append("<li><a href='#' onclick='return keepScrollPos(\"" + targetUrl + "?page=" + i + queryParams + "\");'>" + i + "</a></li>");
                    }
                }
            }
        } else { // 中间页
            for (int i = currentPage - 2; i <= currentPage + 2; i++) {
                if (i > 0 && i <= totalPage) {
                    if (i == currentPage) {
                        pageCode.append("<li class='active'><a href='#'>" + i + "</a></li>");
                    } else {
                        pageCode.append("<li><a href='#' onclick='return keepScrollPos(\"" + targetUrl + "?page=" + i + queryParams + "\");'>" + i + "</a></li>");
                    }
                }
            }
        }

        // 下一页
        if (currentPage == totalPage) {
            pageCode.append("<li class='disabled'><a href='#'><i class='fa fa-angle-right'></i></a></li>");
        } else {
            pageCode.append("<li><a href='#' onclick='return keepScrollPos(\"" + targetUrl + "?page=" + (currentPage + 1) + queryParams + "\");'><i class='fa fa-angle-right'></i></a></li>");
        }

        // 尾页
        pageCode.append("</ul>");

        return pageCode.toString();
    }
}